// pages/chat/chat.js
const app = getApp()
const recorderManager = wx.getRecorderManager()
const getFaceList = require('../../utils/face.js')
const innerAudioContext = wx.createInnerAudioContext()
var msgList = []
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataInfo: {},
    chatlog: {},
    user_id: '',
    openid: '',
    showVoice: false,
    inputValue: '',
		scrollTop: '',
		headImg: '',
		faceList: [],
		showface: '',
		bottomShow: '',
		chat_main: 'scroll',
		chat_extra: 'chat_bottom',
		userMsg: '',
		currentAudio: ''
  },

  // 点击切换输入方式
  changeInputMethod: function() {
    this.setData({
      showVoice: !this.data.showVoice
    })
  },

  // 输入框值的变化
  inputContain: function(e) {
    console.log(e.detail.value)
    this.setData({
      inputValue: e.detail.value
    })
  },

	// 点击表情图标
	clickFaceIcon: function () {
		this.setData({
			bottomShow: 'showface',
			chat_main: 'scroll_showbottom',
			chat_extra: 'chat_bottom_showbottom'
		})
	},

	// 点击加号图标
	clickExtraIcon: function () {
		this.setData({
			bottomShow: 'showextra',
			chat_main: 'scroll_showbottom',
			chat_extra: 'chat_bottom_showbottom'
		})
	},

	// 点击聊天部分
	clickChatMain: function () {
		this.setData({
			bottomShow: '',
			chat_main: 'scroll',
			chat_extra: 'chat_bottom'
		})
	},

	// 输入表情
	inputFace: function (e) {
		var that = this
		console.log(e.currentTarget.dataset.face)
		that.data.inputValue += e.currentTarget.dataset.face
		that.setData({
			inputValue: that.data.inputValue
		})
	},

	// 点击播放语音
	clickVoice: function () {
		var that = this
		var url = app.globalData.baseImgUrl + '/uploads/20181204/9972d3535142b912cef8dba49e444c7d.mp3'
		if (that.data.currentAudio === url) {
			innerAudioContext.stop()
			that.setData({
				currentAudio: ''
			})
		} else {
			that.setData({
				currentAudio: url
			})
			innerAudioContext.src = url
			innerAudioContext.play()
		}
	},

	// 点击上传图片
	clickUploadImg: function () {
		var that = this
		//先获取mediaId
		wx.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				// tempFilePath可以作为img标签的src属性显示图片
				const tempFilePaths = res.tempFilePaths
				// 上传图片文件
				wx.uploadFile({
					url: app.globalData.baseUrl + '/api/csuser/getmediaid	',
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						appid: that.data.dataInfo.user_info.appid,
						type: 'image'
					},
					success: function (res) {
						console.log(res)
						if (res.statusCode === 200) {
							var data = JSON.parse(res.data)
							console.log(data)
							// 通过获取的图片的media_id，发送图片消息给用户
							if (data.status === 1) {
								console.log(data)
								var index = that.data.chatlog.length // 保存此条消息的索引
								that.data.chatlog.push({
									content: app.globalData.baseImgUrl + data.path,
									send_time: that.timeChange(data.send_time),
									send_type: 1002,
									type: 'image',
									loading: 'loading'
								})
								that.setData({
									chatlog: that.data.chatlog,
									scrollTop: that.data.chatlog.length * 150
								})
								that.sendImageMessage(data, index)
							}
						}
					}
				})
			}
		})
	},

	// 发送图片消息给用户
	sendImageMessage: function (data, index) {
		var that = this
		var send_time = Date.parse(new Date()) / 1000
		wx.request({
			url: app.globalData.baseUrl + '/api/user/imgmsg',
			// url: 'https://wechat.shangning.site/api/User/sengImgForUser',
			method: 'POST',
			data: {
				appid: that.data.dataInfo.user_info.appid,
				content: data.path,
				cs_id: that.data.dataInfo.user_info.id,
				media_id: data.media_id,
				openid: that.data.openid,
				send_time: send_time,
				send_type: 1002,
				type: 'image'
			},
			success: function (res) {
				console.log(res)
				if (res.data.status === 1) {
					that.data.chatlog[index].loading = false
					that.setData({
						chatlog: that.data.chatlog
					})
				} else {
					that.data.chatlog[index].loading = 'false'
					that.setData({
						chatlog: that.data.chatlog
					})
				}
			}
		})
	},
  // 点击发送文本消息
  clickSendTextMessage: function() {
    if (this.data.inputValue === '') {
      wx.showToast({
        title: '请先输入内容',
        icon: 'none',
        duration: 1000
      })
    } else {
      this.sendTextMessage()
    }
  },

  // 发送文本消息的请求
  sendTextMessage: function() {
    var that = this
		var index = that.data.chatlog.length // 保存此条消息的索引
		var send_time = Date.parse(new Date()) / 1000
		console.log(index)
		that.data.chatlog.push({
			content: that.data.inputValue,
			send_time: that.timeChange(send_time),
			send_type: 1002,
			type: 'text',
			loading: 'loading'
		})
		console.log(index)
		that.setData({
			chatlog: that.data.chatlog,
			scrollTop: that.data.chatlog.length * 150
		})
    var data = {
      appid: this.data.dataInfo.user_info.appid,
      content: this.data.inputValue,
      cs_id: this.data.dataInfo.user_info.id,
      send_time: send_time,
      send_type: 1002,
      type: 'text',
      user_id: this.data.user_id,
      openid: this.data.openid
    }
    console.log(data)
    wx.request({
      url: app.globalData.baseUrl + '/api/user/textmsg',
      method: 'POST',
      data: data,
      success: function(res) {
        if (res.data.status === 1) {
					that.data.chatlog[index].loading = false
					that.setData({
						chatlog: that.data.chatlog,
						inputValue: ''
					})
				} else {
					that.data.chatlog[index].loading = 'false'
					that.setData({
						chatlog: that.data.chatlog,
						inputValue: ''
					})
				}
      }
    })
  },

	// 点击标签跳转
	clickTag: function () {
		var userMsg = JSON.stringify(this.data.userMsg)
		wx.navigateTo({
			url: '../tag/tag?userMsg=' + userMsg
		})
	},

  // 长按录音事件
  longpressVoice: function() {
    console.log('aaa')
    const options = {
      duration: 10000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'aac',
      frameSize: 50
    }
    wx.showLoading({
      title: '录音中',
    })
    recorderManager.start(options)
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onError((res) => {
      if (res.errMsg === 'operateRecorder:fail DevicesNotFoundError') {
        wx.hideLoading()
        wx.showToast({
          title: '未找到录音设备',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },

  // 结束录音事件
  stopVoice: function() {
    recorderManager.stop()
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res)
      const {
        tempFilePath
      } = res
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(option) {
		var data = JSON.parse(option.msg)
		console.log(data)
    var that = this
		// 设置导航title
    wx.setNavigationBarTitle({
			title: data.nickname
    })
		var faceList = that.split_array(getFaceList, 21)
		console.log(faceList)
    this.setData({
			user_id: Number(data.user_id),
			openid: data.openid,
			headImg: data.headimgurl,
			faceList: faceList
    })
		

    // 获取缓存里面的客服信息
    try {
      var value = wx.getStorageSync('islogin')
      if (value) {
        console.log(value)
        // 如果缓存里面有登录信息则发送请求
				value.user_info.header_url = app.globalData.baseImgUrl + value.user_info.header_url
        this.setData({
          dataInfo: value
        })
      } else {}
    } catch (e) {
      console.log(e)
    }

    // 获取聊天信息
		this.getChatRecord(data.openid)

		// 获取用户信息
		this.getUserMsg(data.openid)
		var that = this;

		
		const innerAudioContext = wx.createInnerAudioContext()
  },



  // 获取聊天信息
  getChatRecord: function(openid) {
    var that = this
    // 获取当前的时间戳（秒）
    var timestamp = Date.parse(new Date()) / 1000
    wx.request({
      url: app.globalData.baseUrl + '/api/user/getchatlog',
      method: 'POST',
      data: {
        cs_id: this.data.dataInfo.user_info.id,
        last_time: timestamp,
        openid: openid
      },
      success: function(res) {
        if (res.data.status === 1) {
          that.setChatRecord(res.data.chatlog)
        }
      }
    })
  },

	// 获取用户信息
	getUserMsg: function (openid) {
		var that = this
		wx.request({
			url: app.globalData.baseUrl + '/api/user/getsqluser',
			method: 'GET',
			data: {
				openid: openid
			},
			success: function (res) {
				if (res.data.status === 1) {
					that.setData({
						userMsg: res.data.result
					})
				}
			}
		})
	},

  // 设置聊天记录的数据，并按照时间戳排序
  setChatRecord: function(chatlog) {
    var that = this
		// 倒序
		chatlog.reverse()
    chatlog.forEach(function(item) {
      item.send_time = that.timeChange(item.send_time)
			if (item.type === 'image' && item.content.slice(0, 7) !== 'http://') {
				item.content = app.globalData.baseImgUrl + item.content
			}
    })
    this.setData({
      chatlog: chatlog,
			scrollTop: chatlog.length * 150
    })
		console.log(that.data.chatlog)
  },

  // 排序的方法
  compare: function(property) {
    return function(a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  },

  // 将时间戳转换为时间
  timeChange: function(timestamp) {
    var date = new Date(timestamp * 1000) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-'
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return Y + M + D + h + m + s
  },

	// 分割数组的方法
	split_array: function (arr, len) {
		var a_len = arr.length;
		var result = []
		for(var i = 0; i < a_len; i+=len) {
			result.push(arr.slice(i, i + len))
		}
		return result
	}, 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
	onShow: function () {
		var that = this;
		app.sureConnect()
		wx.onSocketOpen(function (res) {
			that.onopen(res)
		})

		wx.onSocketMessage(function (res) {
			that.onmessage(res)
		})

	},

	onopen: function (res) {
		console.log(res)
	},

	onmessage: function (res) {
		var that = this
		// console.log(res)
		var data = JSON.parse(res.data)
		if (data.event === 're_connect') {
			app.heartbeat()
		} else if (data.event === 'heartbeat_new') {
			app.heartbeat()
		} else if (data.event === 'sendMsg') {
			console.log(data)
			if (data.data.openid === this.data.openid) {
				if (data.data.type === 'image' && data.data.content.slice(0, 7) !== 'http://') {
					data.data.content = app.globalData.baseImgUrl + data.data.content
				}
				data.data.send_time = that.timeChange(data.data.send_time)
				that.data.chatlog.push(data.data)
				that.setData({
					chatlog: that.data.chatlog,
					scrollTop: that.data.chatlog.length * 150
				})
			} else {
				msgList.push(data.data)
			}
		}
	},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
		// webSocket.closeSocket();
		wx.setStorage({
			key: "newMsgList",
			data: msgList
		})
		msgList = []
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})